{% extends 'base.html' %}
{% load static %}

{% block title %}文件日志查看 - CFS Web System{% endblock %}

{% block page_type %}analytics-file-logs{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item"><a href="{% url 'analytics:dashboard' %}">数据分析</a></li>
<li class="breadcrumb-item active">文件日志</li>
{% endblock %}

{% block content %}
<!-- 日志控制面板 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-file-alt me-2"></i>文件日志查看器
                    </h6>
                    <div class="d-flex gap-2 align-items-center">
                        <span class="badge bg-info" id="log-file-name">加载中...</span>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="auto-refresh" checked>
                            <label class="form-check-label" for="auto-refresh">
                                自动刷新
                            </label>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshLogs()">
                            <i class="fas fa-sync"></i> 刷新
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">日志级别</label>
                        <select class="form-select" id="log-level" onchange="filterLogs()">
                            <option value="">全部</option>
                            <option value="DEBUG">DEBUG</option>
                            <option value="INFO">INFO</option>
                            <option value="WARNING">WARNING</option>
                            <option value="ERROR">ERROR</option>
                            <option value="CRITICAL">CRITICAL</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">显示条数</label>
                        <select class="form-select" id="log-limit" onchange="filterLogs()">
                            <option value="50">50条</option>
                            <option value="100" selected>100条</option>
                            <option value="200">200条</option>
                            <option value="500">500条</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">关键词搜索</label>
                        <input type="text" class="form-control" id="search-keyword" placeholder="搜索日志内容..." onkeyup="searchLogs()">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="button" class="btn btn-outline-secondary w-100" onclick="clearSearch()">
                            <i class="fas fa-times"></i> 清除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 日志统计 -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-info">
                <i class="fas fa-list"></i>
            </div>
            <div class="stat-content">
                <h3 id="total-logs">-</h3>
                <p>总日志数</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-danger">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="stat-content">
                <h3 id="error-logs">-</h3>
                <p>错误日志</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-warning">
                <i class="fas fa-exclamation"></i>
            </div>
            <div class="stat-content">
                <h3 id="warning-logs">-</h3>
                <p>警告日志</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-success">
                <i class="fas fa-info-circle"></i>
            </div>
            <div class="stat-content">
                <h3 id="info-logs">-</h3>
                <p>信息日志</p>
            </div>
        </div>
    </div>
</div>

<!-- 日志内容 -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-terminal me-2"></i>日志内容
                    </h6>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="exportLogs()">
                            <i class="fas fa-download"></i> 导出
                        </button>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="toggleWrap()">
                            <i class="fas fa-text-width"></i> 换行
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="log-viewer" id="log-viewer">
                    <div class="log-loading text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2 text-muted">正在加载日志...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
.log-viewer {
    height: 600px;
    overflow-y: auto;
    background-color: #1e1e1e;
    color: #d4d4d4;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.4;
}

.log-line {
    padding: 2px 15px;
    border-bottom: 1px solid #333;
    white-space: nowrap;
    overflow-x: auto;
}

.log-line:hover {
    background-color: #2d2d30;
}

.log-line.wrap {
    white-space: pre-wrap;
    word-break: break-all;
}

.log-timestamp {
    color: #569cd6;
    margin-right: 10px;
}

.log-level {
    margin-right: 10px;
    font-weight: bold;
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 11px;
}

.log-level.DEBUG {
    background-color: #6c757d;
    color: white;
}

.log-level.INFO {
    background-color: #0dcaf0;
    color: white;
}

.log-level.WARNING {
    background-color: #ffc107;
    color: black;
}

.log-level.ERROR {
    background-color: #dc3545;
    color: white;
}

.log-level.CRITICAL {
    background-color: #6f42c1;
    color: white;
}

.log-message {
    color: #d4d4d4;
}

.log-message.highlight {
    background-color: #ffd700;
    color: #000;
}

.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: white;
}

.stat-content h3 {
    margin: 0;
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.stat-content p {
    margin: 0;
    color: #666;
    font-size: 14px;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
let autoRefreshInterval;
let currentLogs = [];
let filteredLogs = [];

// 页面加载完成后初始化
$(document).ready(function() {
    loadLogs();
    
    // 设置自动刷新
    $('#auto-refresh').change(function() {
        if (this.checked) {
            startAutoRefresh();
        } else {
            stopAutoRefresh();
        }
    });
    
    // 开始自动刷新
    startAutoRefresh();
});

// 加载日志
function loadLogs() {
    const level = $('#log-level').val();
    const limit = $('#log-limit').val();
    
    $.ajax({
        url: '/analytics/ajax/log_data/',
        method: 'GET',
        data: {
            source: 'file',
            level: level,
            limit: limit
        },
        success: function(response) {
            if (response.success) {
                currentLogs = response.logs;
                filteredLogs = currentLogs;
                displayLogs(filteredLogs);
                updateStats();
                
                if (response.log_file) {
                    $('#log-file-name').text(response.log_file);
                }
            } else {
                showLogError('加载日志失败: ' + response.error);
            }
        },
        error: function() {
            showLogError('网络错误，无法加载日志');
        }
    });
}

// 显示日志
function displayLogs(logs) {
    const viewer = $('#log-viewer');
    
    if (logs.length === 0) {
        viewer.html('<div class="text-center py-5 text-muted">没有找到日志记录</div>');
        return;
    }
    
    let html = '';
    logs.forEach(function(log) {
        html += `
            <div class="log-line" data-level="${log.level}">
                <span class="log-timestamp">${log.created_at}</span>
                <span class="log-level ${log.level}">${log.level}</span>
                <span class="log-message">${escapeHtml(log.message)}</span>
            </div>
        `;
    });
    
    viewer.html(html);
    
    // 滚动到底部
    viewer.scrollTop(viewer[0].scrollHeight);
}

// 更新统计信息
function updateStats() {
    const total = currentLogs.length;
    const errorCount = currentLogs.filter(log => log.level === 'ERROR').length;
    const warningCount = currentLogs.filter(log => log.level === 'WARNING').length;
    const infoCount = currentLogs.filter(log => log.level === 'INFO').length;
    
    $('#total-logs').text(total);
    $('#error-logs').text(errorCount);
    $('#warning-logs').text(warningCount);
    $('#info-logs').text(infoCount);
}

// 过滤日志
function filterLogs() {
    const level = $('#log-level').val();
    
    if (level) {
        filteredLogs = currentLogs.filter(log => log.level === level);
    } else {
        filteredLogs = currentLogs;
    }
    
    // 应用搜索过滤
    const keyword = $('#search-keyword').val();
    if (keyword) {
        searchInLogs(keyword);
    } else {
        displayLogs(filteredLogs);
    }
}

// 搜索日志
function searchLogs() {
    const keyword = $('#search-keyword').val().toLowerCase();
    searchInLogs(keyword);
}

function searchInLogs(keyword) {
    if (!keyword) {
        displayLogs(filteredLogs);
        return;
    }
    
    const searchResults = filteredLogs.filter(log => 
        log.message.toLowerCase().includes(keyword)
    );
    
    displayLogs(searchResults);
    
    // 高亮搜索关键词
    $('.log-message').each(function() {
        const text = $(this).text();
        const highlightedText = text.replace(
            new RegExp(keyword, 'gi'),
            '<mark>$&</mark>'
        );
        $(this).html(highlightedText);
    });
}

// 清除搜索
function clearSearch() {
    $('#search-keyword').val('');
    $('#log-level').val('');
    loadLogs();
}

// 刷新日志
function refreshLogs() {
    loadLogs();
}

// 开始自动刷新
function startAutoRefresh() {
    stopAutoRefresh();
    autoRefreshInterval = setInterval(function() {
        if ($('#auto-refresh').is(':checked')) {
            loadLogs();
        }
    }, 5000); // 每5秒刷新一次
}

// 停止自动刷新
function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
    }
}

// 切换换行
function toggleWrap() {
    $('.log-line').toggleClass('wrap');
}

// 导出日志
function exportLogs() {
    const logs = filteredLogs.map(log => 
        `${log.created_at} [${log.level}] ${log.message}`
    ).join('\n');
    
    const blob = new Blob([logs], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `cfs_logs_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

// 显示错误信息
function showLogError(message) {
    $('#log-viewer').html(`
        <div class="text-center py-5">
            <i class="fas fa-exclamation-triangle text-warning fa-3x mb-3"></i>
            <p class="text-muted">${message}</p>
            <button class="btn btn-primary" onclick="loadLogs()">重试</button>
        </div>
    `);
}

// 注意：showError, showToast, showSuccess, showWarning, showInfo 等通知函数已在 main.js 中全局定义

// HTML转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});
</script>
{% endblock %}